package com.simple.cms.common.interceptor;


import com.simple.cms.common.constants.Loggers;
import com.simple.cms.common.enums.ResultCode;
import com.simple.cms.common.exception.BizException;
import com.simple.cms.common.exception.SystemException;
import com.simple.cms.common.result.CommonResult;
import org.springframework.beans.ConversionNotSupportedException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class RestApiControlAdvice {

    private static final String METHOD_THROWN_KEY = "diagnostic.method.thrown";

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResult handleException(final HttpServletRequest request, Exception e) {
        Loggers.ERROR_LOGGER.error("系统异常：", e);
        CommonResult commonResult = new CommonResult(ResultCode.SYSTEM_ERROR);
        request.setAttribute(METHOD_THROWN_KEY, commonResult);
        return commonResult;
    }

    @ExceptionHandler(value = SystemException.class)
    @ResponseBody
    public CommonResult handleSystemException(final HttpServletRequest request, SystemException e) {
        Loggers.ERROR_LOGGER.error("自定义系统异常：", e);
        CommonResult commonResult = new CommonResult(e.getCode(), e.getMsg());
        request.setAttribute(METHOD_THROWN_KEY, commonResult);
        return commonResult;
    }

    @ExceptionHandler(value = BizException.class)
    @ResponseBody
    public CommonResult handleBizException(final HttpServletRequest request, final BizException e) {
        CommonResult commonResult = new CommonResult(e.getCode(), e.getMsg());
        request.setAttribute(METHOD_THROWN_KEY, commonResult);
        return commonResult;
    }

}
